package com.gt.wxpay.cashier.common;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * packageName com.gt.wxpay.cashier.common
 *
 * @author GuoTong
 * @version JDK 8
 * @className RedisLockUtils
 * @date 2024/3/18
 * @description Redis分布式锁工具类
 */
public class RedisLockUtils {

    private static volatile RedisTemplate<String, Object> redisTemplate;

    // 获取RedisTemplate实例
    @SuppressWarnings("unchecked")
    private static RedisTemplate<String, Object> getRedisTemplate() {
        if (redisTemplate == null) {
            synchronized (RedisLockUtils.class) {
                if (redisTemplate == null) {
                    redisTemplate = SpringBeanUtil.getBean("redisTemplate", RedisTemplate.class);
                }
            }
        }
        return redisTemplate;
    }

    /**
     * lockKey 锁 key
     * value 身份标识（保证锁不会被其他人释放）
     * expireTime 锁的有效时间
     **/
    public static Boolean lock(String lockKey, String value, long expireTime) {
        try {
            return getRedisTemplate().opsForValue().setIfAbsent(lockKey, value, expireTime, TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new RuntimeException("redis连接异常");
        }
    }

    /**
     * key 锁的key
     * value 身份标识
     * return 成功返回true 失败返回false
     **/
    public static Boolean unlock(String key, String value) {
        // 获取当前锁的拥有者
        Object currentValue = getRedisTemplate().opsForValue().get(key);
        Boolean result = false;
        // 判断value是否为锁的拥有者
        if (StringUtils.isNotEmpty(String.valueOf(currentValue)) && Objects.equals(currentValue, value)) {
            //删除锁
            result = getRedisTemplate().opsForValue().getOperations().delete(key);
        }
        return result;
    }

}
